package reflect;

import java.lang.reflect.Field;

public class ReflectDemo8 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Teacher teacher = new Teacher();
        teacher.name="范传奇";
        System.out.println(teacher.name);

        Class cls = Class.forName("reflect.Teacher");
        Object obj = cls.newInstance();
        /*
            Field是反射对象之一，他的每一个实例用于表示某个类中的某个属性
         */
        //获取属性
        Field field = cls.getField("name");//获取Teacher类中名为"name"的属性
        field.set(obj,"王克晶");//obj.name="王克晶"
        System.out.println(field.get(obj));// System.out.println(obj.name);

        //给age设置值并输出
        Field field1 = cls.getDeclaredField("age");
        field1.setAccessible(true);
        field1.set(obj,18);
        System.out.println(field1.get(obj));
        field1.setAccessible(false);
    }
}
